package com.xu.ai.mcp.syncclient;

import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * 阻塞式mcp客户端启动类
 *
 * @author xuguan
 * @since 2025/11/3
 */
@SpringBootApplication
public class SyncClientApplication {
	public static void main(String[] args) {
		SpringApplication.run(SyncClientApplication.class, args);
	}

	@Bean
	public CommandLineRunner toolCallback(List<McpSyncClient> mcpSyncClients,
										  ToolCallbackProvider toolCallbackProvider,
										  ChatClient.Builder chatClientBuilder,
										  ObjectMapper objectMapper) {
		return new CommandLineRunner() {
			@Override
			public void run(String... args) throws Exception {
				final McpSyncClient mcpSyncClient = mcpSyncClients.stream()
						.filter(client -> client.getClientInfo().name().contains("server1"))
						.findFirst().orElseThrow(() -> new RuntimeException("No client found"));
				final McpSchema.ListToolsResult listToolsResult = mcpSyncClient.listTools();
				System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(listToolsResult));
			}
		};
	}
}
